package firstShallowPersistencePackagev;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.swing.JOptionPane;

/*
 * Created on 16/08/2005
 *
 * TODO To change the template for this generated file go to
 *Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author malice
 * 
 *         TODO To change the template for this generated type comment go to
 *         Window - Preferences - Java - Code Style - Code Templates
 */

public class TableEntry implements Serializable {
	private static final long serialVersionUID = 42L;

	private Integer id;
	private Class c;
	private Object o;
	private String objFName;

	/**
	 * 
	 */
	public TableEntry(Integer idObj, Object ob) {
		super();
		this.id = idObj;
		this.c = ob.getClass();
		this.o = ob;
		this.objFName = "fObj" + idObj.toString();
	}

	public Object read() {
		try {
			FileInputStream fileIn = new FileInputStream(objFName);
			ObjectInputStream in = new ObjectInputStream(fileIn);
			o = c.cast(in.readObject());
		} catch (Exception e) {
			javax.swing.JOptionPane.showMessageDialog(null,
					"reading file Exception: " + e);
		}
		return (c.cast(o));
	}

	public Object getObj(Integer idObj) {
		if (id.equals(idObj))
			if (o == null)
				return (c.cast(read()));
			else
				return (c.cast(o));
		else
			return (c.cast(null));
	}

	public Integer getId() {
		return (id);
	}

	public void write() {
		if (o != null) {
			try {
				FileOutputStream fileOut = new FileOutputStream(objFName);
				ObjectOutputStream out = new ObjectOutputStream(fileOut);
				out.writeObject(c.cast(o));
			} catch (Exception e) {
				javax.swing.JOptionPane.showMessageDialog(null,
						"The write ( ) in object id " + id.intValue()
								+ " caused an Writing File Exception!" + e);
			}
			;
		}
	}

	public void put(Object ob) {
		o = c.cast(ob);
		write();
	}

	public void close() {
		o = (Object) null;
	}

	public void display() {
		JOptionPane.showMessageDialog(
				null,
				"Broker/entry -  Id:  " + id.intValue() + "  Class:  "
						+ c.getName() + "  File name:  " + objFName);
	}

	public Object runMethod(Object proxy, Method met, Object[] args)
			throws Throwable {
		Object r;
		if (o == null)
			read();
		try {
			r = met.invoke(c.cast(o), args);
		} catch (InvocationTargetException e) {
			throw e.getTargetException();
		}
		;
		return r;
	}
}